﻿using Model.Entitys;
using Shop.Interface.Repository;
using Shop.Models.Common;
using SqlSugar;
using SqlSugar.IOC;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Shop.Services.Repository
{
    public class BaseRepository:IBaseRepository
    {
        public ISqlSugarClient Db { get; }

        public BaseRepository(ISqlSugarClient context=null)
        {
            context = DbScoped.Sugar;
            context.DbMaintenance.CreateDatabase();
            context.CodeFirst.InitTables(
                typeof(Log4Net),
                typeof(Users),
                typeof(Menu),
                typeof(Role),
                typeof(UserRoleRelation),
                typeof(MenuRoleRelation)
                );
            Db = context;
        }

        public async Task<bool> CreateAsync<TEntity>(TEntity t) where TEntity : class,new ()
        {
            var result = await Db.Insertable(t).ExecuteCommandAsync();
            return result>0;
        }

        public async Task<bool> DeleteById<TEntity>(string id) where TEntity : class, new()
        {
            var result = await Db.Deleteable<TEntity>().In(id).ExecuteCommandAsync() > 0;
            return result;
        }

        public List<TEntity> GetAll<TEntity>() where TEntity : class, new()
        {
            return Db.Queryable<TEntity>().ToList();
        }

        public TEntity GetById<TEntity>(string id) where TEntity : class, new()
        {
            return Db.Queryable<TEntity>().InSingle(id);
        }

        public long GetCount<TEntity>() where TEntity : class, new()
        {
            return Db.Queryable<TEntity>().Count();
        }

        public List<TEntity> Querry<TEntity>(Expression<Func<TEntity, bool>> func) where TEntity : class, new()
        {
            return Db.Queryable<TEntity>().Where(func).ToList();
        }

        public List<TEntity> Querry<TEntity>(int page, int size, ref int total) where TEntity : class, new()
        {
            return Db.Queryable<TEntity>().ToPageList(page, size, ref total);
        }

        public List<TEntity> Querry<TEntity>(Expression<Func<TEntity, bool>> func, int page, int size, ref int total) where TEntity : class, new()
        {
            return Db.Queryable<TEntity>().Where(func).ToPageList(page, size, ref total);
        }

        public bool Update<TEntity>(TEntity t) where TEntity : class, new()
        {
            var x = Db.Updateable(t).ExecuteCommand();
            return x > 0;
        }

        public async Task<bool> DeleteAsync<TEntity>(TEntity t) where TEntity : class, new()
        {
            var x= await Db.Deleteable(t).ExecuteCommandAsync();
            return x > 0;
        }

        public async Task<bool> BatchDelete<TEntity>(string[] ids) where TEntity : BaseId, new()
        {
            var list = Querry<TEntity>(p=>ids.Contains(p.Id.ToString()));
            return await Db.Deleteable(list).ExecuteCommandAsync() > 0;
        }
    }
}
